/*
 * @Author: xinyang3
 * @Date: 2021-10-05 08:56:01
 * @LastEditTime: 2022-03-10 14:45
 * @LastEditors: xinyang3
 * @Description: blog router
 */
import router from './router.js';
import * as CollectionBlog from '../collection/blog.js';
import fs from 'fs';
import { Buffer } from 'buffer';
import { default as compressing } from 'compressing';
import dateFmt from '../util/date-fmt.js';

const RegFile = /^(sfiles)\[([\d]*)\]$/;
const RegFileIcon = /^(sfilesIcon)\[([\d]*)\]$/;
const RegImages = /^(images)\[([\d]*)\]$/;
const url_prifix = '/bgmg/blog';

const stringify = (result, size) => {
  return JSON.stringify({
    type: 'succss',
    state: 200,
    data: result,
    size: size,
  });
};

// const fileMatch = (file, data) => {
//   let fileData = null;
//   let type = file.type;
//   if (type == 'md') {
//     fileData = convertToHtml(data);
//   } else if (type == 'pdf') {
//     fileData = Buffer.from(data, 'binary');
//   }
//   return fileData;
// };

// 插入
router.post(`${url_prifix}/insert`, async function (ctx, next) {
  const { request, response } = ctx;

  const data = request.body;
  data.sfiles = [];
  data.images = [];
  data.sfilesIcon = [];
  const files = request.files;

  Object.keys(files).forEach(async (key) => {
    let match = null;
    if (key.match(RegFile)) {
      match = key.match(RegFile);
    } else if (key.match(RegFileIcon)) {
      match = key.match(RegFileIcon);
    } else if (key.match(RegImages)) {
      match = key.match(RegImages);
    }

    let file = files[key],
      json = {},
      // encoding = file.type.indexOf('image') >= 0 ? 'binary' : 'utf8',
      type = file.name.substr(file.name.lastIndexOf('.') + 1);

    let fdata = await fs.readFileSync(file.path);
    json.size = file.size;
    json.data = fdata;
    json.name = file.name;
    json.originType = file.type;
    json.type = type;

    data[match[1]][match[2]] = json;
  });
  const result = await CollectionBlog.insertOne(data);
  response.body = stringify(result);
});
// 修改
router.post(`${url_prifix}/update`, async function (ctx, next) {
  const { request, response } = ctx;
  const data = request.body;
  data.sfiles = [];
  data.images = [];
  data.sfilesIcon = [];
  const files = request.files;

  Object.keys(files).forEach(async (key) => {
    let match = null;
    if (key.match(RegFile)) {
      match = key.match(RegFile);
    } else if (key.match(RegFileIcon)) {
      match = key.match(RegFileIcon);
    } else if (key.match(RegImages)) {
      match = key.match(RegImages);
    }

    let file = files[key],
      json = {},
      // encoding = file.type.indexOf('image') >= 0 ? null : { encoding: 'utf8' },
      type = file.name.substr(file.name.lastIndexOf('.') + 1);

    let fdata = await fs.readFileSync(file.path);
    json.size = file.size;
    json.data = fdata;
    json.name = file.name;
    json.originType = file.type;
    json.type = type;
    data[match[1]][match[2]] = json;
  });

  const result = await CollectionBlog.updateOne(data);
  response.body = stringify(result);
});
// 删除
router.delete(`${url_prifix}/deleteOne`, async function (ctx, next) {
  const { request, response } = ctx;
  const data = request.query;
  var result = await CollectionBlog.deleteOne(data);
  response.body = stringify(result);
});

// 博客列表
router.get(`${url_prifix}/list`, async function ({ response, request }, next) {
  const query = request.query;
  const result = await CollectionBlog.query(query);
  const results = await CollectionBlog.queryAll(query);
  result.forEach((item) => {
    const file = item.sfiles && item.sfiles.length > 0 ? item.sfiles[0] : {};
    // file.data = null;
    item.file = file;
  });

  response.body = stringify(result, results.length);
});

// 博客详情页面展示
router.get(
  `${url_prifix}/detail/:id`,
  async function ({ request, response }, next) {
    const { id } = request.params;
    const result = await CollectionBlog.queryOne({
      _id: id,
    });
    if (result) {
      result.sfiles &&
        result.sfiles.forEach((file) => {
          if (file.type == 'md') {
            file.data = Buffer.isBuffer(file.data.buffer)
              ? file.data.buffer.toString()
              : file.data;
          }
        });
      // result.images &&
      //   result.images.forEach((image) => {
      //     if (image.type == 'md') {
      //       image.data = image.data.buffer;
      //     }
      //   });
    }
    response.body = JSON.stringify({
      type: 'success',
      state: 200,
      data: result,
    });
  }
);

// 博客详情页面展示带参数md pdf
router.get(
  `${url_prifix}/detail/file/:id`,
  async function ({ request, response }, next) {
    const { id } = request.params;
    const result = await CollectionBlog.queryOne({
      _id: id,
    });
    if (result) {
      result.sfiles &&
        result.sfiles.forEach((file) => {
          if (file.type == 'md') {
            file.data = file.data.buffer.toString();
          } else if (file.type == 'pdf') {
            file.data = Buffer.from(file.data.buffer, 'binary');
          }
        });
      result.images = [];
    }
    response.body = JSON.stringify({
      type: 'success',
      state: 200,
      data: result,
    });
  }
);

// 博客详情页面展示md,pdf
router.get(`${url_prifix}/detail/download/:id`, async function (ctx, next) {
  const { request, response } = ctx;
  const { id } = request.params;

  const result = await CollectionBlog.queryOne({
    _id: id,
  });

  const zipStream = new compressing.zip.Stream();
  if (result) {
    if (result.sfiles && result.sfiles.length > 0) {
      result.sfiles.forEach((file) => {
        zipStream.addEntry(file.data.buffer, {
          relativePath: file.name,
        });
      });
    }
    if (result.images && result.images.length > 0) {
      result.images.forEach((image) => {
        zipStream.addEntry(image.data.buffer, {
          relativePath: image.name,
        });
      });
    }
  }
  if (zipStream) {
    const zip_name = `blog-${dateFmt(new Date(), 'yyyyMMdd')}-${Math.round(
      Math.random() * 1000
    )}.zip`;
    response.set('Content-Type', 'application/octet-stream');
    response.attachment(zip_name);
    response.body = zipStream;
  } else {
    response.body = stringify({
      error: 'file compress error.',
    });
  }
});

// 博客详情页面图片获取
router.get(
  `${url_prifix}/detail/:id/:name`,
  async function ({ request, response }, next) {
    const { id, type, name } = request.params;
    const colect = await CollectionBlog.queryOne({
      _id: id,
    });

    let { images } = colect;
    let result = null;
    if (images && images.length > 0) {
      let match = images.filter((img) => name && img.name && img.name == name);
      if (match.length > 0) {
        const image = match[0];
        result = image.data.buffer;
        response.set('Content-Type', `${image.originType};charset=UTF-8`);
      }
    }
    response.set('Accept-Ranges', 'bytes');
    response.body = result;
  }
);
// 博客详情页面图片获取
router.get(
  `${url_prifix}/detail/:id/imageicons/:name`,
  async function ({ request, response }, next) {
    const { id, type, name } = request.params;
    const colect = await CollectionBlog.queryOne({
      _id: id,
    });

    let { sfilesIcon } = colect;
    let result = null;
    if (sfilesIcon && sfilesIcon.length > 0) {
      let match = sfilesIcon.filter(
        (img) => name && img.name && img.name == name
      );
      if (match.length > 0) {
        const image = match[0];
        result = image.data.buffer;
        response.set('Content-Type', `${image.originType};charset=UTF-8`);
      }
    }
    response.set('Accept-Ranges', 'bytes');
    response.body = result;
  }
);
